<template>
  <div class="box">
    <header class="header">购物车</header>
    <div class="content">
      <van-empty description="购物车里什么都没有" v-if="flag">
        <van-button round type="danger" class="bottom-button" @click="$router.push('/home')">
          去逛逛
        </van-button>
      </van-empty>
      <div class="" v-else>
        <van-swipe-cell v-for="(item,idx) in cartList" :key="item.proId">
          <van-card
            :price="item.price"
            :desc="item.time"
            :title="item.proName"
            class="goods-card"
          >
            <template #thumb>
              <van-checkbox v-model="item.flag" @click="selFlag(idx)"></van-checkbox>
              <van-image :src="item.proImg" fit="cover" />
            </template>
            <template #num>
              <van-stepper v-model="item.num" theme="round" button-size="22" @change="change" :name="item.proId" />
            </template>
          </van-card>
          <template #right>
            <van-button square text="删除" type="danger" class="delete-button" @click="del(item.proId, idx)" />
          </template>
        </van-swipe-cell>
        <van-submit-bar :price="priceSum" button-text="提交订单" @submit="onSubmit">
          <van-checkbox v-model="allSelFlag">全选</van-checkbox>
          <template #tip>
            您选择了 <span style="font-size:24px">{{proSum}}</span> 件商品
          </template>
        </van-submit-bar>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { SwipeCell, Card, Button, Empty, Stepper, SubmitBar, Checkbox, Image as VanImage } from 'vant'

import { getCart, getDetail, updateCartNum, delCart, updateFlag, updateAllFlag } from '../../api/index.js'

Vue.use(SwipeCell)
Vue.use(Card)
Vue.use(Button)
Vue.use(Empty)
Vue.use(Stepper)
Vue.use(SubmitBar)
Vue.use(Checkbox)
Vue.use(VanImage)

export default {
  beforeRouteEnter (to, from, next) {
    if (localStorage.getItem('isLogin') === 'ok') {
      next()
    } else {
      next('/login?to=' + to.path)
    }
  },
  data () {
    return {
      cartList: []
    }
  },
  computed: {
    // 利用计算属性,实现空状态和列表的切换
    flag () {
      // 根据数据的长度计算
      return this.cartList.length < 1
    },
    // 计算总数量
    proSum () {
      return this.cartList.reduce((prev, next) => {
        return prev + (next.num - 0)
      }, 0)
    },
    // 计算总价
    priceSum () {
      return this.cartList.reduce((prev, next) => {
        return prev + (next.num - 0) * next.price
      }, 0)
    },
    // 计算全选效果
    allSelFlag: {
      // 通过选中 单个商品 决定是否选中 全选
      get () {
        return this.cartList.every(val => {
          return val.flag
        })
      },
      // 通过选中 全选, 决定是否选中 所有商品
      set (val) {
        for (let i = 0; i < this.cartList.length; i++) {
          this.cartList[i].flag = val
        }
        updateAllFlag({
          userId: localStorage.getItem('userId'),
          flag: val
        }).then(res => {
          // console.log('全部更新成功')
        })
      }
    }
  },
  methods: {
    change (val, detail) {
      // console.log(val, detail)
      updateCartNum({
        userId: localStorage.getItem('userId'),
        proId: detail.name,
        num: val
      }).then(res => {
        // console.log(res)
        // console.log('这是修改数量成功后的回调函数')
      })
    },
    del (id, i) {
      // 删除接口
      delCart({
        userId: localStorage.getItem('userId'),
        proId: id
      }).then(res => {
        console.log(id)
        this.cartList.splice(i, 1)
      })
    },
    onSubmit () {},
    selFlag (i) {
      // console.log(this.cartList[i].proId, this.cartList[i].flag)
      updateFlag({
        userId: localStorage.getItem('userId'),
        proId: this.cartList[i].proId,
        flag: this.cartList[i].flag
      }).then(res => {
        // console.log('选中状态更新成功')
      })
    }
  },
  mounted () {
    getCart({
      userId: localStorage.getItem('userId')
    }).then(res => {
      if (res.data.state === 200) {
        // this.cartList = res.data.data.proData
        const arr = res.data.data.proData
        arr.forEach(val => {
          getDetail({
            id: val.proId
          }).then(data => {
            const obj = data.data.data
            obj.num = val.num
            obj.time = val.time + ''
            obj.flag = val.flag
            this.cartList.push(obj)
          })
        })
        console.log(this.cartList)
      } else {
        console.log('没有数据，空的购物车')
      }
    })
  }
}
</script>

<style lang="scss">
.delete-button {
  height: 100%;
}
.van-card__thumb{
  display: flex;
  width:1.2rem;
  img{
    width:88px
  }
  .van-checkbox{
    margin-right:0.1rem
  }
}
</style>
